<template>
  <div class="crm-contact">
    <el-card shadow="never">
      <template #header>
        <div class="crm-contact__header">
          <span>联系人管理</span>
          <div>
            <el-button type="primary" size="small" @click="openCreate">新增</el-button>
            <el-button size="small" type="danger" :disabled="multipleSelection.length===0" @click="onBatchDelete">批量删除</el-button>
          </div>
        </div>
      </template>
      <el-form :inline="true" class="crm-contact__search" @submit.prevent>
        <el-form-item label="客户">
          <el-select
            v-model="query.customerId"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="remoteCustomer"
            :loading="loadingCustomer"
            placeholder="输入客户编码/名称"
            style="width: 200px"
          >
            <el-option v-for="c in customerOptions" :key="c.customerId" :label="`${c.customerCode} | ${c.customerName}`" :value="String(c.customerId)" />
          </el-select>
        </el-form-item>
        <el-form-item label="联系人姓名">
          <el-input v-model="query.contactName" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="query.phone" clearable placeholder="支持模糊" />
        </el-form-item>
        <el-form-item label="角色类型">
          <el-select v-model="query.roleType" placeholder="全部" clearable>
            <el-option value="DECISION_MAKER" label="决策人" />
            <el-option value="PURCHASER" label="采购人" />
            <el-option value="USER" label="使用人" />
          </el-select>
        </el-form-item>
        <el-form-item label="主要联系人">
          <el-select v-model="query.isPrimary" placeholder="全部" clearable>
            <el-option :value="1" label="是" />
            <el-option :value="0" label="否" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="query.status" placeholder="全部" clearable>
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSearch">查询</el-button>
          <el-button size="small" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>

      <el-table :data="list" size="small" style="width: 100%" @selection-change="onSelectionChange">
        <el-table-column type="selection" width="48" />
        <el-table-column prop="contactName" label="联系人姓名" min-width="120" />
        <el-table-column prop="customerId" label="所属客户ID" min-width="120" />
        <el-table-column prop="position" label="职位" min-width="120" />
        <el-table-column prop="department" label="部门" min-width="120" />
        <el-table-column prop="phone" label="手机号" min-width="120" />
        <el-table-column prop="tel" label="固定电话" min-width="120" />
        <el-table-column prop="email" label="邮箱" min-width="160" />
        <el-table-column prop="wechat" label="微信" min-width="120" />
        <el-table-column prop="roleType" label="角色类型" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="row.roleType === 'DECISION_MAKER'" type="danger">决策人</el-tag>
            <el-tag v-else-if="row.roleType === 'PURCHASER'" type="warning">采购人</el-tag>
            <el-tag v-else-if="row.roleType === 'USER'" type="info">使用人</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isPrimary" label="主要联系人" min-width="100">
          <template #default="{ row }">
            <el-tag :type="row.isPrimary === 1 ? 'success' : 'info'">{{ row.isPrimary === 1 ? '是' : '否' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" min-width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">{{ row.status === 1 ? '启用' : '停用' }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="160" />
        <el-table-column label="操作" width="160" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" size="small" @click="openEdit(row)">编辑</el-button>
            <el-popconfirm title="确认删除该联系人？" @confirm="onDelete(row)">
              <template #reference>
                <el-button link type="danger" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <div class="crm-contact__pagination">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          :current-page="pageNum"
          @size-change="onSizeChange"
          @current-change="onPageChange"
        />
      </div>
    </el-card>

    <el-drawer v-model="drawerVisible" :with-header="true" :title="drawerTitle" size="600px">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="所属客户" prop="customerId">
          <el-input
            v-model="form.customerNameDisplay"
            readonly
            placeholder="点击选择客户"
            style="width: 100%"
            @click="openCustomerSelector"
          >
            <template #append>
              <el-button @click="openCustomerSelector">选择客户</el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="联系人姓名" prop="contactName">
          <el-input v-model="form.contactName" maxlength="64" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="请选择" style="width: 100%" clearable>
            <el-option :value="1" label="男" />
            <el-option :value="2" label="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="position">
          <el-input v-model="form.position" maxlength="100" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="form.department" maxlength="100" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" maxlength="32" />
        </el-form-item>
        <el-form-item label="固定电话" prop="tel">
          <el-input v-model="form.tel" maxlength="32" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" maxlength="128" />
        </el-form-item>
        <el-form-item label="微信" prop="wechat">
          <el-input v-model="form.wechat" maxlength="64" />
        </el-form-item>
        <el-form-item label="QQ" prop="qq">
          <el-input v-model="form.qq" maxlength="32" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="form.address" type="textarea" :rows="2" maxlength="500" />
        </el-form-item>
        <el-form-item label="生日" prop="birthday">
          <el-date-picker v-model="form.birthday" type="date" placeholder="选择日期" value-format="YYYY-MM-DD" style="width: 100%" />
        </el-form-item>
        <el-form-item label="角色类型" prop="roleType">
          <el-select v-model="form.roleType" placeholder="请选择" style="width: 100%" clearable>
            <el-option value="DECISION_MAKER" label="决策人" />
            <el-option value="PURCHASER" label="采购人" />
            <el-option value="USER" label="使用人" />
          </el-select>
        </el-form-item>
        <el-form-item label="主要联系人" prop="isPrimary">
          <el-switch v-model="form.isPrimary" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择" style="width: 100%">
            <el-option :value="1" label="启用" />
            <el-option :value="0" label="停用" />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div style="flex: 1; text-align: center">
          <el-button @click="drawerVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitLoading" @click="submitForm">保存</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- 客户选择器 -->
    <CrmCustomerSelector v-model="customerSelectorVisible" @confirm="handleCustomerSelected" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { pageContact, createContact, updateContact, getContact, deleteContact, deleteContactBatch } from '@/api/crm/contact'
import { pageCustomer, getCustomer } from '@/api/crm/customer'
import CrmCustomerSelector from '@/components/CrmCustomerSelector/index.vue'
import { ElMessage } from 'element-plus'

interface ContactForm {
  contactId?: string
  customerId: string
  contactName: string
  gender?: number
  position?: string
  department?: string
  phone?: string
  tel?: string
  email?: string
  wechat?: string
  qq?: string
  address?: string
  birthday?: string
  roleType?: 'DECISION_MAKER' | 'PURCHASER' | 'USER'
  isPrimary: number
  status: number
  remark?: string
}

const list = ref<any[]>([])
const tableRef = ref()
const selectedIds = ref<Set<string>>(new Set())
const total = ref(0)
const pageNum = ref(1)
const pageSize = ref(10)
const query = reactive<{
  customerId?: string
  contactName?: string
  phone?: string
  roleType?: string
  isPrimary?: number
  status?: number | ''
}>({
  customerId: '',
  contactName: '',
  phone: '',
  roleType: '',
  isPrimary: undefined,
  status: ''
})
const multipleSelection = ref<any[]>([])

const drawerVisible = ref(false)
const isEdit = ref(false)
const drawerTitle = ref('新增联系人')
const formRef = ref<FormInstance>()
const form = reactive<ContactForm & { customerNameDisplay?: string }>({
  customerId: '',
  customerNameDisplay: '',
  contactName: '',
  gender: undefined,
  position: '',
  department: '',
  phone: '',
  tel: '',
  email: '',
  wechat: '',
  qq: '',
  address: '',
  birthday: '',
  roleType: undefined,
  isPrimary: 0,
  status: 1,
  remark: ''
})

// 客户选择器
const customerSelectorVisible = ref(false)

const openCustomerSelector = () => {
  customerSelectorVisible.value = true
}

const handleCustomerSelected = (customer: any) => {
  form.customerId = String(customer.customerId)
  form.customerNameDisplay = `${customer.customerCode} | ${customer.customerName}`
}
const rules: FormRules = {
  customerId: [{ required: true, message: '请选择所属客户', trigger: 'change' }],
  contactName: [{ required: true, message: '请输入联系人姓名', trigger: 'blur' }]
}
const submitLoading = ref(false)

// 客户下拉选项
const customerOptions = ref<any[]>([])
const loadingCustomer = ref(false)

const remoteCustomer = async (query: string) => {
  if (!query || query.length < 2) {
    customerOptions.value = []
    return
  }
  loadingCustomer.value = true
  try {
    const res = await pageCustomer({
      pageNum: 1,
      pageSize: 20,
      customerCode: query,
      customerName: query
    })
    customerOptions.value = res?.data?.records || []
  } catch (error) {
    console.error('加载客户列表失败:', error)
  } finally {
    loadingCustomer.value = false
  }
}

const load = async () => {
  const res = await pageContact({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    customerId: query.customerId || undefined,
    contactName: query.contactName || undefined,
    phone: query.phone || undefined,
    roleType: query.roleType || undefined,
    isPrimary: query.isPrimary,
    status: query.status === '' ? undefined : String(query.status)
  })
  list.value = res?.data?.records || []
  total.value = res?.data?.total || 0
}

const onPageChange = (p: number) => {
  pageNum.value = p
  load()
}
const onSizeChange = (s: number) => {
  pageSize.value = s
  pageNum.value = 1
  load()
}

const onSearch = () => {
  pageNum.value = 1
  load()
}

const onReset = () => {
  query.customerId = ''
  query.contactName = ''
  query.phone = ''
  query.roleType = ''
  query.isPrimary = undefined
  query.status = ''
  onSearch()
}

const resetForm = () => {
  form.contactId = undefined
  form.customerId = ''
  form.customerNameDisplay = ''
  form.contactName = ''
  form.gender = undefined
  form.position = ''
  form.department = ''
  form.phone = ''
  form.tel = ''
  form.email = ''
  form.wechat = ''
  form.qq = ''
  form.address = ''
  form.birthday = ''
  form.roleType = undefined
  form.isPrimary = 0
  form.status = 1
  form.remark = ''
}

const openCreate = () => {
  isEdit.value = false
  drawerTitle.value = '新增联系人'
  resetForm()
  drawerVisible.value = true
}

const openEdit = async (row: any) => {
  isEdit.value = true
  drawerTitle.value = '编辑联系人'
  resetForm()
  try {
    const res = await getContact(String(row.contactId))
    const data = res?.data || {}
    Object.assign(form, {
      ...data,
      contactId: String(data.contactId),
      customerId: String(data.customerId),
      birthday: data.birthday ? String(data.birthday).substring(0, 10) : ''
    })
    // 加载客户名称用于显示
    if (data.customerId) {
      try {
        const customerRes = await getCustomer(String(data.customerId))
        const customer = customerRes?.data
        if (customer) {
          form.customerNameDisplay = `${customer.customerCode} | ${customer.customerName}`
        }
      } catch (error) {
        console.error('加载客户信息失败:', error)
      }
    }
    drawerVisible.value = true
  } catch (error) {
    ElMessage.error('加载联系人信息失败')
  }
}

const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const payload = {
          ...form,
          customerId: String(form.customerId)
        }
        if (isEdit.value) {
          await updateContact(String(form.contactId!), payload as any)
          ElMessage.success('更新成功')
        } else {
          await createContact(payload as any)
          ElMessage.success('新增成功')
        }
        drawerVisible.value = false
        load()
      } catch (error: any) {
        ElMessage.error(error?.message || '保存失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

const onDelete = async (row: any) => {
  try {
    await deleteContact(String(row.contactId))
    ElMessage.success('删除成功')
    load()
  } catch (error: any) {
    ElMessage.error(error?.message || '删除失败')
  }
}

const onBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  try {
    const ids = multipleSelection.value.map((row: any) => String(row.contactId))
    await deleteContactBatch(ids)
    ElMessage.success('批量删除成功')
    load()
  } catch (error: any) {
    ElMessage.error(error?.message || '批量删除失败')
  }
}

const onSelectionChange = (selection: any[]) => {
  multipleSelection.value = selection
}

onMounted(() => {
  load()
})
</script>

<style scoped lang="scss">
.crm-contact {
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  &__search {
    margin-bottom: 12px;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

